//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"context"

	"atomgit.com/openlinksaas-org/proxy/redis_pkg/gen_code"
	"github.com/go-redis/redis/v8"
)

type CmdApiImpl struct{}

func (s *CmdApiImpl) ExecPost(ctx context.Context, req gen_code.ExecPostRequest) (gen_code.ImplResponse, error) {
	if req.Token != token {
		return gen_code.ImplResponse{
			Code: 500,
			Body: gen_code.ErrInfo{
				ErrMsg: "wrong token",
			},
		}, nil
	}
	infoItem, ok := clientMap.Load(req.Id)
	if !ok {
		return gen_code.ImplResponse{
			Code: 500,
			Body: gen_code.ErrInfo{
				ErrMsg: "redis connection not exist",
			},
		}, nil
	}
	info := infoItem.(*ClientInfo)
	args := []any{}
	for _, arg := range req.Args {
		args = append(args, arg)
	}
	var result any
	var err error
	if info.Cluster {
		c := info.client.(*redis.ClusterClient)
		result, err = c.Do(ctx, args...).Result()
	} else {
		c := info.client.(*redis.Client)
		result, err = c.Do(ctx, args...).Result()
	}
	if err != nil {
		return gen_code.ImplResponse{
			Code: 500,
			Body: gen_code.ErrInfo{
				ErrMsg: err.Error(),
			},
		}, nil
	}
	return gen_code.ImplResponse{
		Code: 200,
		Body: result,
	}, nil
}
